package com.rbs.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.rbs.common.Constants;
import org.springframework.web.bind.annotation.*;
import jakarta.annotation.Resource;
import com.rbs.common.Result;
import java.util.List;

import com.rbs.service.ICustDistrictService;
import com.rbs.entity.CustDistrict;

import org.springframework.web.bind.annotation.RestController;

/**
 * <p>
 * 地区表 前端控制器
 * </p>
 *
 * @author lisl
 * @since 2024-04-07
 */
@RestController
@RequestMapping("/cust-district")
public class CustDistrictController {

    @Resource
    private ICustDistrictService custDistrictService;

    //新增/修改
    @PostMapping("/saveAndUpdate")
    public Result saveAndUpdate(@RequestBody CustDistrict custDistrict){
        if (custDistrict.getCdStrdistrict()!="") {
            boolean flag=custDistrictService.findSameDistrictname(custDistrict);
            if (flag==false){
                //地区名不存在，保存新的
                return Result.success(custDistrictService.saveOrUpdate(custDistrict));
            }else {
                //地区名存在
                return Result.error("地区名已经存在");
            }
        }else {
            return Result.error(Constants.CODE_400,"地区名不能为空！");
        }
    }

    //按名称模糊查询
    //传空值时返回全部
    @GetMapping("/findByName")
    public Result findByName(@RequestBody CustDistrict custDistrict){
        List<CustDistrict> cList=custDistrictService.findDistrictName(custDistrict);
        return Result.success(cList);
    }

    //按id删除
    @DeleteMapping("/{id}")
    public Result delete(@PathVariable Integer id) {
        return Result.success(custDistrictService.removeById(id));
    }

    //批量删除
    @PostMapping("/del/batch")
    public Result deleteBatch(@RequestBody List<Integer> ids) {
        return Result.success(custDistrictService.removeBatchByIds(ids));
    }

    //查找全部
    @GetMapping("/findAll")
    public Result findAll() {
        return Result.success(custDistrictService.list());
    }

    //按id查询
    @GetMapping("/{id}")
    public Result findOne(@PathVariable Integer id) {
        return Result.success(custDistrictService.getById(id));
    }

    //按id排序，true从大到小，false从小到大
    @GetMapping("/orderById")
    public Result descByID(@RequestParam boolean descOrAsc,
                           @RequestParam Integer pageNum,
                           @RequestParam Integer pageSize){

        QueryWrapper<CustDistrict> queryWrapper = new QueryWrapper<>();
        if (descOrAsc==true){
            queryWrapper.orderByDesc("id");
        }else if (descOrAsc==false){
            queryWrapper.orderByAsc("id");
        }
        return Result.success(custDistrictService.page(new Page<>(pageNum, pageSize), queryWrapper));
    }
}

